<?php
/*
 module:		礼物记录
 create_time:	2022-03-07 18:03:51
 author:	陕西格创
 contact:
*/

namespace app\api\controller;

use app\api\model\ZhBalanceLog as ZhBalanceLogModel;
use app\api\model\ZhExchangeSetting;
use app\api\service\ZhExchangeService;
use app\backend\model\SysSite as SysSiteModel;
use app\api\model\Member as MemberModel;
use think\db\Where;
use think\facade\Db;

class ZhExchange extends Common
{

    /**
     * 获取兑换列表
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function index()
    {
        $wxapp_id = $this->request->get('wxapp_id');
        $uId      = $this->request->uid;
//        $uId = 347;

        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }

        $limit = $this->request->get('limit', 20, 'intval');
        $page  = $this->request->get('page', 1, 'intval');

        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        if (!$user) {
            return $this->ajaxReturn($this->errorCode, '未知用户');
        }

        $where             = [];
        $where['wxapp_id'] = $wxapp_id;
        $field             = '*';
        $orderby           = 'id desc';


        $res = ZhExchangeService::indexList($uId, formatWhere($where), $field, $orderby, $limit, $page);
        foreach ($res['list'] as &$v) {
            if ($v['exchange_uid'] != $uId) {
                $exchangeUserData       = MemberModel::where([
                    'uid'      => $v['exchange_uid'],
                    'wxapp_id' => $wxapp_id])->find();
                $v['exchange_nickname'] = $exchangeUserData['real_name'];
                $v['exchange_avatar']   = $exchangeUserData['avatar'];
                $v['nickname']          = $user['real_name'];
                $v['avatar']            = $user['avatar'];
                $v['authentication_id'] = \app\api\model\ZhAuthentication::where('u_id', '=', $v['exchange_uid'])->value('authentication_id');
            } else {
                $exchangeUserData       = MemberModel::where([
                    'uid'      => $v['u_id'],
                    'wxapp_id' => $wxapp_id])->find();
                $v['nickname']          = $exchangeUserData['real_name'];
                $v['avatar']            = $exchangeUserData['avatar'];
                $v['exchange_nickname'] = $user['real_name'];
                $v['exchange_avatar']   = $user['avatar'];
                $v['authentication_id'] = \app\api\model\ZhAuthentication::where('u_id', '=', $v['u_id'])->value('authentication_id');
            }

            $v['createtime'] = date('Y-m-d H:i:s', $v['createtime']);
        }
        unset($v);
        return $this->ajaxReturn($this->successCode, '返回成功', htmlOutList($res));
    }

    public function count()
    {
        $wxapp_id = $this->request->get('wxapp_id');
        $uId      = $this->request->uid;
//        $uId      = 347;

        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }

        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        if (!$user) {
            return $this->ajaxReturn($this->errorCode, '未知用户');
        }

        $where             = [];
        $where['wxapp_id'] = $wxapp_id;
        $where['status']   = 0;
        $field             = '*';
        $orderby           = 'id desc';

        $res = ZhExchangeService::indexList($uId, formatWhere($where), $field, $orderby, 1, 1);
        return $this->ajaxReturn($this->successCode, '返回成功', [
            'un_handle' => $res['count']
        ]);
    }

    /**
     * 处理交换
     *
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function handle()
    {
        $wxapp_id = $this->request->post('wxapp_id');
        $uId      = $this->request->post('uid');
//        $uId      = 347;
        $id     = $this->request->post('id', '', 'serach_in');// 记录id
        $status = $this->request->post('status', '', 'serach_in');// 记录id
        // status 交换状态 0交换中，1接收交换，2拒绝交换，3交换过期
        if (!in_array($status, ['1', '2'])) {
            return $this->ajaxReturn($this->errorCode, '操作错误');
        }

        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }

        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }

        if (!$id) {
            return $this->ajaxReturn($this->errorCode, '缺少信息参数');
        }

        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        if (!$user) {
            return $this->ajaxReturn($this->errorCode, '未知用户');
        }

        $exchangeData = \app\api\model\ZhExchange::where([
            'id'           => $id,
            'wxapp_id'     => $wxapp_id,
            'exchange_uid' => $uId,
            'status'       => 0
        ])->find();
        if (empty($exchangeData)) {
            return $this->ajaxReturn($this->errorCode, '操作有误');
        }
        $sUser = MemberModel::where(['uid' => $exchangeData['u_id'], 'wxapp_id' => $wxapp_id])->find();
        if (!$sUser) {
            return $this->ajaxReturn($this->errorCode, '未知用户');
        }

        // 更新状态
        $res = \app\api\model\ZhExchange::where([
            'id'           => $id,
            'wxapp_id'     => $wxapp_id,
            'exchange_uid' => $uId,
            'status'       => 0
        ])->update(['status' => $status]);
        if ($res) {
            // 修改成功
            // 如果拒绝交换，交换次数不为0时退还交换次数，否则退款红心
            if ($status == 2 && $user['exchange_num'] > 0) {
                MemberModel::where(['uid' => $exchangeData['u_id'], 'wxapp_id' => $wxapp_id])
                    ->update(['exchange_num' => Db::raw('exchange_num+1')]);
            } else {
                ZhBalanceLogModel::insert([
                    'u_id'          => $exchangeData['u_id'],
                    'wxapp_id'      => $wxapp_id,
                    'start_balance' => $sUser['virtual_currency_balance'],
                    'end_balance'   => $sUser['virtual_currency_balance'] + $exchangeData['price'],
                    'type'          => '收入',
                    'remake'        => '对方拒绝交换',
                    'create_time'   => time(),
                    'num'           => $exchangeData['price']
                ]);
                MemberModel::where(['uid' => $exchangeData['u_id'], 'wxapp_id' => $wxapp_id])
                    ->update(['virtual_currency_balance' => Db::raw('virtual_currency_balance+' . $exchangeData['price'])]);
            }
        }

        return $this->ajaxReturn($this->successCode, '返回成功');
    }

    /**
     * 过期轮询，每分钟执行一次
     *
     * @return \think\response\Json|void
     */
    function expires()
    {
        $exchangeSerttingData = ZhExchangeSetting::where('id', '=', 1)->find();
        if (!$exchangeSerttingData) {
            return $this->ajaxReturn($this->errorCode, '缺少交换配置');
        }
        //先查询过期的交换
        $data = \app\api\model\ZhExchange::where(['status' => 0, 'createtime' => ['<', time() - 60 * 60 * 24 * $exchangeSerttingData['expires']]])->select();
        if ($data) {
            foreach ($data as $v) {
                // 如果交换次数大于0，优先扣除交换次数
                if ($v['exchange_num'] > 0) {
                    MemberModel::where(['uid' => $v['u_id'], 'wxapp_id' => $v['wxapp_id']])
                        ->update(['exchange_num' => Db::raw('exchange_num+1')]);
                } else {
                    // 修改我的红心余额
                    MemberModel::where(['uid' => $v['u_id'], 'wxapp_id' => $v['wxapp_id']])
                        ->update(['virtual_currency_balance' => Db::raw('virtual_currency_balance+' . $v['price'])]);

                    ZhBalanceLogModel::insert([
                        'u_id'          => $v['u_id'],
                        'wxapp_id'      => $v['wxapp_id'],
                        'start_balance' => $v['virtual_currency_balance'],
                        'end_balance'   => $v['virtual_currency_balance'] + $v['price'],
                        'type'          => '收入',
                        'remake'        => '交换过期',
                        'create_time'   => time(),
                        'num'           => $v['price']
                    ]);
                }
                // 修改状态
                \app\api\model\ZhExchange::where(['id' => $v['id']])->update(['status' => 3]);
            }
        }
    }

    /**
     * 发起交换联系方式
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function send()
    {
        $wxapp_id = $this->request->post('wxapp_id');
        $uId      = $this->request->uid;
        $sid      = $this->request->post('sid', '', 'serach_in');// 交换人id

        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }

        if (!$sid) {
            return $this->ajaxReturn($this->errorCode, '缺少信息参数交换者id');
        }

        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        if (!$user) {
            return $this->ajaxReturn($this->errorCode, '未知用户');
        }

        $sUser = MemberModel::where(['uid' => $sid, 'wxapp_id' => $wxapp_id])->find();
        if (!$sUser) {
            return $this->ajaxReturn($this->errorCode, '未知用户');
        }

        $exchangeSerttingData = ZhExchangeSetting::where('id', '=', 1)->find();
        if (!$exchangeSerttingData) {
            return $this->ajaxReturn($this->errorCode, '缺少交换配置');
        }

        // 查找是否已经有了交换
        $data = \app\api\model\ZhExchange::where(['u_id' => $uId, 'exchange_uid' => $sid, 'status' => 0])->find();
        if ($data) {
            return $this->ajaxReturn($this->errorCode, '耐心等待对方回复');
        }

        // 后台判断用户红心是否足够
        if ($user['exchange_num'] < 1 && $user['virtual_currency_balance'] < $exchangeSerttingData['price']) {
            return $this->ajaxReturn($this->errorCode, '您的红心不足，请先前往充值');
        }

        // 如果交换次数大于0，优先扣除交换次数
        if ($user['exchange_num'] > 0) {
            $totalPrice = 0;
            $remark     = '扣除交换次数';
        } else {
            $totalPrice = $exchangeSerttingData['price'];
            $remark     = '扣除红心';
        }

        // status 交换状态 0交换中，1接收交换，2拒绝交换，3交换过期
        $insertGetId = \app\api\model\ZhExchange::insertGetId([
            'wxapp_id'     => $wxapp_id,
            'price'        => $totalPrice,
            'num'          => 1,
            'u_id'         => $uId,
            'exchange_uid' => $sid,
            'createtime'   => time(),
            'status'       => 0,
            'remark'       => $remark
        ]);
        if ($insertGetId) {
            // 如果交换次数大于0，优先扣除交换次数
            if ($user['exchange_num'] > 0) {
                MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])
                    ->update(['exchange_num' => Db::raw('exchange_num-1')]);
            } else {
                // 修改我的红心余额
                MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])
                    ->update(['virtual_currency_balance' => Db::raw('virtual_currency_balance-' . $totalPrice)]);

                ZhBalanceLogModel::insert([
                    'u_id'          => $uId,
                    'wxapp_id'      => $wxapp_id,
                    'start_balance' => $user['virtual_currency_balance'],
                    'end_balance'   => $user['virtual_currency_balance'] - $totalPrice,
                    'type'          => '支出',
                    'remake'        => '交换联系方式',
                    'create_time'   => time(),
                    'num'           => $totalPrice
                ]);
            }
        }
        return $this->ajaxReturn($this->successCode, '返回成功');
    }

}

